define(function (require, exports, module) {
    var angular = require("angular");
    var common = require('./common');
    var ui = require('ui');
    var util = require('util');
    require("angular-ui");
    require('service/ng_service/projectService');
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/para-setting/"; //api前缀
    angular.module('ProjectReportedRules', ['ProjectService'])
        .service('brokerIdentities', ['$q', '$http', function ($q, $http) {
            /**
             * 所有身份数组
             */
            return function (cache) {
                if (typeof cache == 'undefined') {
                    cache = true;
                }

                var defer = $q.defer();

                $http.get(G_CONFIG.api_prefix + 'qmyx/broker/get-broker-identity-by-token', {cache: cache})
                    .success(function (res) {
                        if (res.retCode == 0) {

                            var data = res.data;
                            var item;
                            for (var i = 0; item = data[i]; i++) {
                                item.value = item.Value;
                                item.name = item.Text;
                            }

                            defer.resolve(data);
                        } else {
                            defer.reject();
                        }
                    })
                    .error(function () {
                        defer.reject();
                    });

                return defer.promise;
            };
        }])    
        .controller('ReportedRulesController', ['$scope', '$http','brokerIdentities', function ($scope, $http,brokerIdentities) {
            $scope.save = function () {
                var data = $scope.data;
                var protectionPattern = data.protectionPattern;
                //由于每日推荐客户上限运行输入空（表示无限制），所以必须在前端校验。
                if(typeof(data.recommendLimit.value)=='undefined' || data.recommendLimit.value == '0'){
                    util.alert("每日推荐客户上限必须大于等于0或者为空。",{'title':'错误'});
                    return;
                }
                $http.post(
                    api_prefix + "save-filing-rule-data",
                    {
                        bhId: protectionPattern.id,
                        bhType: protectionPattern.paravalue,
                        daysRemind: protectionPattern.days_remind,
                        dkdaysRemind: protectionPattern.dkdays_remind,
                        daysBakRemind: protectionPattern.days_bak_remind,

                        proId: $scope.curProjectId,
                        cId: data.consumerConfirmPattern.id,
                        bId: data.bbdkTime.id,
                        sId: data.isEnableSeller.id,
                        recommendLimitId: data.recommendLimit.id,
                        recommendLimit: data.recommendLimit.value,
                        smsId: data.customerRegRemind.id,
                        cPattern: data.consumerConfirmPattern.paraValue,
                        bbdkTime: data.bbdkTime.value,
                        eSeller: data.isEnableSeller.value,
                        smsRemind: data.customerRegRemind.IsEnable,
                        mobile: data.customerRegRemind.Mobiles.join(';') + ";",
                        sTime: $scope.startTimeHour + ':' + $scope.startTimeMinute,
                        eTime: $scope.endTimeHour + ':' + $scope.endTimeMinute,
                        identifications:collectChangedIdentification()
                    }
                )
                    .success(function (res) {
                        ui.showSucTip();
                    })
            };
            //添加手机号
            $scope.addTel = function () {
                common.showMobileInputDialog({
                    ok: function (mobile) {
                        var data = $scope.data;
                        $http.post(
                            api_prefix + "add-reg-remind",
                            {
                                id: data.customerRegRemind.id,
                                mobile: mobile
                            }
                        )
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.data.customerRegRemind.Mobiles.push(mobile);
                                    ui.showSucTip();
                                } else {
                                    ui.showErrTip(res.errMsg);

                                }
                            });
                    }
                });
            };
            //删除短信注册提醒
            $scope.delTel = function (mobile, index) {
                util.confirm("您确定要删除吗？", {
                    ok: function () {
                        $http.post(
                            api_prefix + "del-reg-remind",
                            {
                                type: 1,
                                mobile: mobile,
                                proId: $scope.curProjectId
                            }
                        )
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.data.customerRegRemind.Mobiles.splice(index, 1);
                                    ui.showSucTip();
                                } else {
                                    ui.showErrTip(res.errMsg);
                                }
                            });
                    }
                });
            };

            //指定销售员
            $scope.identifications = null;
            $scope.curIdentification = null;
            var collectChangedIdentification = function(){
                var changedData = {
                    'add':[],
                    'delete':[]                
                };
                $($scope.identifications).each(function(idxId,elId){
                    $(elId.teams).each(function(idxTeam,elTeam){
                        $(elTeam.users).each(function(idxUser,elUser){
                            
                            if($scope.data.isEnableSeller.value == 1){
                                if(elUser.selected && !elUser.originalselected){
                                    // 选择
                                    changedData.add.push({
                                        identification:elId.Value,
                                        p_projectId:$scope.curProjectId,
                                        s_userId:elUser.s_userId
                                    });
                                }
                                else if(!elUser.selected && elUser.originalselected){
                                    // 取消选择
                                    changedData.delete.push(elUser.b_dentification2userId);
                                }
                            }
                            else
                            {
                                if(elUser.originalselected){
                                    // 关闭指定销售员则删除所有设置
                                    changedData.delete.push(elUser.b_dentification2userId);
                                }
                            }
                            
                        });
                    }); 
                });
                
                return changedData;
            };
            var initIdentificationInternal = function(identification,teams,id2user){   
                identification.teams = jQuery.extend(true, [], teams); 
                
                // 先取出当前身份已指定的销售员
                var selectedUsers = [];
                $(id2user).each(function(idx,el){
                    if(el.identification.toLowerCase()==identification.Value.toLowerCase()){
                        selectedUsers.push(el);
                    }
                });
                if(selectedUsers.length==0){
                    return;
                }  
                
                // 遍历销售员，把已指定的销售员打上已选和编辑状态标识(status：1 add，2 delete 0 original)
                $(selectedUsers).each(function(idx,el){
                    var hit = false;
                    $(identification.teams).each(function(idxTeam,elTeam){
                        $(elTeam.users).each(function(idxUser,elUser){
                            if(el.s_userId.toLowerCase() == elUser.s_userId.toLowerCase()){
                                elUser.selected = true; // 选择标识
                                elUser.originalselected = true; // 初始值标识
                                elUser.b_dentification2userId = el.b_dentification2userId;
                                hit = true;
                                return false;
                            }
                        });
                        
                        if(hit){
                            // 一个销售员不可能属于多个团队，所以这里可以跳出循环，优化性能
                            return false;
                        }
                    }); 
                }); 
            };
            $scope.initIdentification = function(projectId){
                $scope.loading = true;
                $http
                    .get(api_prefix + "get-identification2user", {params: {proId: projectId}})
                    .then(function (res) {
                        if (res.data.retCode == 0) {
                            $scope.identifications = res.data.data['brokeridentity'];
                            $($scope.identifications).each(function(index,element){
                                initIdentificationInternal(element,res.data.data['teams'],res.data.data['id2user']);
                            })
                            // 默认选中第一个经纪人身份
                            if($scope.identifications.length>0){
                                $scope.curIdentification = $scope.identifications[0];
                            }
                        }
                        $scope.loading = false;
                    });
            }
            $scope.selectIdentification = function(item){
                $scope.curIdentification = item;
            };
            $scope.checkTeam = function(item){
                $($scope.curIdentification.teams).each(function(idx,el){
                    if(el.s_sales_teamId.toLowerCase()==item.s_sales_teamId.toLowerCase()){
                        $(el.users).each(function(idxUser,elUser){
                            elUser.selected = item.selected; 
                        });
                    }
                });
            };
            
            var update = function (projectId) {
                $http
                    .get(api_prefix + "get-filing-rule-data", {params: {proId: projectId,XDEBUG_SESSION_START:'netbeans-xdebug'}})
                    .then(function (res) {
                        //是否启用指定销售员
                        var data = res.data.data;
                        var enableSeller = data.isEnableSeller;
                        ui.initSwitch('#reported_autocheck', function (data) {
                            enableSeller.value = data.value;
                            if(data.value == 1){
                                $scope.initIdentification(projectId);
                            }
                            else{
                                $scope.curIdentification = null;
                            }
                                
                            $scope.$applyAsync();
                        });
                        if (enableSeller.value == '0') {
                            ui.offSwitch('reported_autocheck');
                        } else {
                            ui.openSwitch('reported_autocheck');
                            $scope.initIdentification(projectId);
                            $scope.$applyAsync();
                        }

                        //新客户提醒短信
                        var customerRegRemind = data.customerRegRemind;
                        ui.initSwitch('#reported_messgecheck', function (data) {
                            customerRegRemind.IsEnable = data.value;
                            $scope.$applyAsync();
                        });
                        if (customerRegRemind.IsEnable == '0') {
                            ui.offSwitch('reported_messgecheck');
                        } else {
                            ui.openSwitch('reported_messgecheck');
                        }

                        var hours = [];
                        for (var i = 0; i < 24; i++) {
                            hours.push(util.pad(i, 2));
                        }
                        $scope.hours = hours;
                        $scope.minutes = ['00', '10', '20', '30', '40', '50', '59'];
                        //发送时间段
                        var split = customerRegRemind.StartTime.split(':');
                        $scope.startTimeHour = split[0];
                        $scope.startTimeMinute = split[1];

                        split = customerRegRemind.EndTime.split(':');
                        $scope.endTimeHour = split[0];
                        $scope.endTimeMinute = split[1];

                        var mobiles = customerRegRemind.Mobiles;
                        mobiles = mobiles.replace(/;$/, '');
                        if (mobiles == '') {
                            customerRegRemind.Mobiles = [];
                        }
                        else {
                            customerRegRemind.Mobiles = mobiles.split(';');
                        }

                        $scope.data = data;
                    })
            };

            $scope.$watch('curProjectId', function () {
                if ($scope.curProjectId) {
                    update($scope.curProjectId);
                }
            });
        }])
});